/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eightbears.beboy.ui.chat.ui.activity;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.cache.GroupMemberCache;
import com.eightbears.beboy.base.cache.MessageStatusCache;
import com.eightbears.beboy.base.cache.TopUserCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.image.circle.ClipImageActivity;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.entity.UpdateGroupEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.event.TopUserEvent;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ChatUtil;
import com.eightbears.beboy.ui.user.activity.UserInfoActivity;
import com.eightbears.greendao.GroupList;
import com.eightbears.greendao.MessageStatus;
import com.eightbears.greendao.TopEaseUser;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMucSharedFile;
import com.hyphenate.chat.EMPushConfigs;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseGroupListener;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseExpandGridView;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.NetUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.GROUP_EXCHANGE_GROUP_COVER;
import static com.eightbears.beboy.base.util.CommonAPI.GROUP_EXCHANGE_GROUP_NAME;
import static com.eightbears.beboy.base.util.CommonAPI.GROUP_TICHU_MEMBER;
import static com.eightbears.beboy.base.util.CommonAPI.GROUP_TUICHU_MEMBER;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_GROUP_COVER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_GROUP_ID;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_GROUP_NAME;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_USERS_ID;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATE_GROUP_ICON;
import static com.eightbears.beboy.ui.chat.ui.activity.NoticeEditActivity.GROUP_DIR_UPDATE;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;

public class GroupDetailsActivity extends BaseActivity {


    public static final String EVENT_GROUP_UPDATE = "groupUpdate";

    private static final String TAG = "GroupDetailsActivity";
    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EXIT = 1;
    private static final int REQUEST_CODE_EXIT_DELETE = 2;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;
    private static final int REQUEST_CODE_EDIT_GROUP_DESCRIPTION = 6;
    private static final int REQUEST_CODE_EDIT_GROUP_EXTENSION = 7;

    // 头像
    private static final int REQUEST_CAPTURE = 100;        //请求相机
    private static final int REQUEST_PICK = 101;          //请求相册
    private static final int REQUEST_CROP_PHOTO = 102;    //请求截图
    private File tempFile;                                //调用照相机返回图片文件
    private String cropImagePath;                         // 剪裁路径


    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.progressBar)
    ProgressBar loadingPB;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.btn_exit_grp)
    Button exitBtn;
    @BindView(R.id.btn_exitdel_grp)
    Button deleteBtn;
    @BindView(R.id.gridview)
    EaseExpandGridView userGridview;
    @BindView(R.id.iv_group_head)
    RoundedImageView iv_group_head;
    @BindView(R.id.tv_group_name)
    TextView tv_group_name;
    @BindView(R.id.tv_description)
    TextView tv_description;
    @BindView(R.id.tb_top_message)
    ToggleButton tb_top_message;
    @BindView(R.id.tb_block_groupmsg)
    ToggleButton tb_block_groupmsg;

    private String groupId;
    private int position;

    private EMGroup group;
    private GridAdapter membersAdapter;
    private ProgressDialog progressDialog;
    private UserEntity.User mUserEntity;
    private GroupList mGroupList;

    public static GroupDetailsActivity instance;


    private EMPushConfigs pushConfigs;

    private String operationUserId = "";
    String memberText = "";

    private List<String> memberList = Collections.synchronizedList(new ArrayList<String>());
    private List<String> muteList = Collections.synchronizedList(new ArrayList<String>());
    private List<String> blackList = Collections.synchronizedList(new ArrayList<String>());

    GroupChangeListener groupChangeListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        groupId = getIntent().getStringExtra("groupId");
        group = EMClient.getInstance().groupManager().getGroup(groupId);
        position = getIntent().getIntExtra(CommonAPI.EXTAR_POSITION, -1);
        mGroupList = GroupCache.getInstance(this).getCacheById(groupId);
        mUserEntity = SPUtil.getUser().getData();
        if (group == null) {
            finish();
            return;
        }

        setContentView(R.layout.em_activity_group_details);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        instance = this;
        groupChangeListener = new GroupChangeListener();
        setDescription();
        memberText = getResources().getString(R.string.people);
        tv_group_name.setText(group.getGroupName());
        tv_title.setText(group.getGroupName() + "(" + group.getMemberCount() + memberText);

        if (group.getOwner() == null || "".equals(group.getOwner())
                || !group.getOwner().equals(EMClient.getInstance().getCurrentUser())) {
            exitBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.GONE);
        }

        // show dismiss button if you are owner of group
        if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())) {
            exitBtn.setVisibility(View.GONE);
            deleteBtn.setVisibility(View.VISIBLE);
        }

        String groupCover;
        if (null != mGroupList) {
            groupCover = mGroupList.getCover();
        } else {
            groupCover = R.mipmap.qun_touxiang + "";
        }

        CommonUtils.loadImageView(this, groupCover, R.mipmap.qun_touxiang, iv_group_head);

        //get push configs
        pushConfigs = EMClient.getInstance().pushManager().getPushConfigs();
        EMClient.getInstance().groupManager().addGroupChangeListener(groupChangeListener);

        MessageStatus messageStatus = MessageStatusCache.getInstance(getApplicationContext()).getCacheById(groupId);
        if (null != messageStatus) {
            tb_block_groupmsg.setChecked(true);
        } else {
            tb_block_groupmsg.setChecked(false);
        }
        TopEaseUser topEaseUser = TopUserCache.getInstance(getBaseContext()).getCacheById(groupId);
        if (null != topEaseUser) {
            tb_top_message.setChecked(true);
        } else {
            tb_top_message.setChecked(false);
        }
    }

    @Override
    protected void initData() {
        membersAdapter = new GridAdapter(this, R.layout.em_grid_owner, new ArrayList<String>());
        userGridview.setAdapter(membersAdapter);
        updateGroup();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        userGridview.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (membersAdapter.isInDeleteMode) {
                            membersAdapter.isInDeleteMode = false;
                            membersAdapter.notifyDataSetChanged();
                            return true;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        v.performClick();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        tb_top_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    EventBus.getDefault().post(new TopUserEvent(position, groupId, true));
                } else {
                    EventBus.getDefault().post(new TopUserEvent(position, groupId, false));
                }
            }
        });
        tb_block_groupmsg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    MessageStatusCache.getInstance(getApplicationContext()).saveData(new MessageStatus(groupId));
                } else {
                    MessageStatusCache.getInstance(getApplicationContext()).removeDataById(groupId);
                }
            }
        });
    }

    @OnClick(R.id.clear_all_history)
    void clearHistory() {
        String st9 = getResources().getString(R.string.sure_to_empty_this);
        new EaseAlertDialog(GroupDetailsActivity.this, null, st9, null, new EaseAlertDialog.AlertDialogUser() {
            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if (confirmed) {
                    clearGroupHistory();
                }
            }
        }, true).show();
    }

    /**
     * 退群
     */
    @OnClick(R.id.btn_exit_grp)
    void exitGroup() {
        startActivityForResult(new Intent(this, ExitGroupDialog.class), REQUEST_CODE_EXIT);
    }

    /**
     * 删除群聊
     */
    @OnClick(R.id.btn_exitdel_grp)
    void deleteGroup() {
        startActivityForResult(new Intent(this, ExitGroupDialog.class).putExtra("deleteToast", getString(R.string.dissolution_group_hint)),
                REQUEST_CODE_EXIT_DELETE);

    }

    @OnClick(R.id.rl_change_group_name)
    void changeGroupName() {
        if (group.getOwner() == null || "".equals(group.getOwner())
                || !group.getOwner().equals(EMClient.getInstance().getCurrentUser())) {
            return;
        }
        startActivityForResult(new Intent(this, EditActivity.class)
                .putExtra("data", group.getGroupName()), REQUEST_CODE_EDIT_GROUPNAME);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @OnClick(R.id.rl_group_head)
    void updateHead() {
        showImageDialog();
    }

    @OnClick(R.id.rl_notice)
    void GroupNotice() {
        startLocalActivity(this, NoticeEditActivity.class, PARAMS_GROUP_ID, groupId);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    public void setDescription() {
        String content = group.getDescription();
        if (content.toString().trim().equals("")) {
            tv_description.setText("暂无公告");
        } else {
            tv_description.setText(content);
        }
    }

    private void showImageDialog() {
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup(this);
        bottomSelectionPopup.setTxCancel(getResources().getString(R.string.btn_cancel));
        bottomSelectionPopup.setTx_1Text(getResources().getString(R.string.text_select_image));
        bottomSelectionPopup.setTx_2Text(getResources().getString(R.string.text_select_capture));
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        selectPicture();
                        break;
                    case R.id.ll_2:
                        getCapture();
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }

    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    private void getCapture() {
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(CommonAPI.CACHE_HEAD_FILE), System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    /**
     * 根据Uri返回文件绝对路径, file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    boolean isCurrentOwner(EMGroup group) {
        String owner = group.getOwner();
        if (owner == null || owner.isEmpty()) {
            return false;
        }
        return owner.equals(EMClient.getInstance().getCurrentUser());
    }

    /**
     * 修改图片
     */
    public void postUserImage() {
        OkHttpUtils.post().url(URL_UPDATE_GROUP_ICON)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("group_id", groupId)
                .addFile("cover", "cover_group_" + groupId, new File(cropImagePath))
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                UpdateGroupEntity updateGroupEntity = GsonUtil.fromJson(response, UpdateGroupEntity.class);

                if (updateGroupEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    CommonUtils.loadImageView(GroupDetailsActivity.this, cropImagePath, R.mipmap.qun_touxiang, iv_group_head);
                    mGroupList.setCover(updateGroupEntity.getData().getCover());
                    GroupCache.getInstance(GroupDetailsActivity.this).updateGroup(mGroupList);
                    EventBus.getDefault().post(EVENT_GROUP_UPDATE);
                    ChatUtil.sendCMSMessage(GROUP_EXCHANGE_GROUP_COVER, PARAMS_GROUP_COVER,
                            updateGroupEntity.getData().getCover(), groupId, mUserEntity.getUser_id());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(GroupDetailsActivity.this, status_error);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String st1 = getResources().getString(R.string.being_added);
        String st2 = getResources().getString(R.string.is_quit_the_group_chat);
        String st3 = getResources().getString(R.string.chatting_is_dissolution);
        String st4 = getResources().getString(R.string.are_empty_group_of_news);
        final String st5 = getResources().getString(R.string.is_modify_the_group_name);
        final String st6 = getResources().getString(R.string.Modify_the_group_name_successful);
        final String st7 = getResources().getString(R.string.change_the_group_name_failed_please);

        final String st8 = getResources().getString(R.string.is_modify_the_group_description);
        final String st9 = getResources().getString(R.string.Modify_the_group_description_successful);
        final String st10 = getResources().getString(R.string.change_the_group_description_failed_please);
        final String st11 = getResources().getString(R.string.Modify_the_group_extension_successful);
        final String st12 = getResources().getString(R.string.change_the_group_extension_failed_please);

        switch (requestCode) {
            case REQUEST_CAPTURE:
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:
                if (null != data) {
                    Uri pickUri = data.getData();
                    gotoClipActivity(pickUri);
                }

                break;
            case REQUEST_CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri cropUri = data.getData();
                    if (cropUri == null) {
                        return;
                    }
                    cropImagePath = getRealFilePathFromUri(getApplicationContext(), cropUri);
                    postUserImage();
                }
                break;
        }

        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setMessage(st1);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
                case REQUEST_CODE_ADD_USER:// 添加群成员
                    final String[] newmembers = data.getStringArrayExtra("newmembers");
                    progressDialog.setMessage(st1);
                    progressDialog.show();
                    addMembersToGroup(newmembers);
                    break;
                case REQUEST_CODE_EXIT: // 退出群
                    progressDialog.setMessage(st2);
                    progressDialog.show();
                    exitGrop();
                    break;
                case REQUEST_CODE_EXIT_DELETE: // 解散群
                    progressDialog.setMessage(st3);
                    progressDialog.show();
                    deleteGrop();
                    break;

                case REQUEST_CODE_EDIT_GROUPNAME: //修改群名称
                    final String returnData = data.getStringExtra("data");
                    if (!TextUtils.isEmpty(returnData)) {
                        progressDialog.setMessage(st5);
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    ChatUtil.sendCMSMessage(GROUP_EXCHANGE_GROUP_NAME, PARAMS_GROUP_NAME,
                                            returnData, groupId, mUserEntity.getUser_id());
                                    EMClient.getInstance().groupManager().changeGroupName(groupId, returnData);
                                    GroupList groupList = GroupCache.getInstance(getApplicationContext()).getCacheById(groupId);
                                    if (null != groupList) {
                                        groupList.setGroupname(returnData);
                                        GroupCache.getInstance(getApplicationContext()).updateGroup(groupList);
                                        EventBus.getDefault().post(EVENT_GROUP_UPDATE);
                                    }
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            tv_title.setText(group.getGroupName() + "(" + group.getMemberCount() + ")");
                                            tv_group_name.setText(returnData);
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st6, Toast.LENGTH_SHORT).show();
                                        }
                                    });

                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st7, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                    break;
                case REQUEST_CODE_EDIT_GROUP_DESCRIPTION:
                    final String returnData1 = data.getStringExtra("data");
                    if (!TextUtils.isEmpty(returnData1)) {
                        progressDialog.setMessage(st5);
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    EMClient.getInstance().groupManager().changeGroupDescription(groupId, returnData1);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st9, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st10, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                    break;
                case REQUEST_CODE_EDIT_GROUP_EXTENSION: {
                    final String returnExtension = data.getStringExtra("data");
                    if (!TextUtils.isEmpty(returnExtension)) {
                        progressDialog.setMessage(st5);
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    EMClient.getInstance().groupManager().updateGroupExtension(groupId, returnExtension);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st11, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st12, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                }
                break;

                default:
                    break;
            }
        }
    }


    private void refreshMembersAdapter() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                membersAdapter = new GridAdapter(GroupDetailsActivity.this, R.layout.em_grid_owner, new ArrayList<String>());
                membersAdapter.clear();
                synchronized (memberList) {
                    membersAdapter.addAll(memberList);
                }

                synchronized (muteList) {
                    membersAdapter.addAll(EMClient.getInstance().getCurrentUser());
                }
                synchronized (blackList) {
                    membersAdapter.addAll(blackList);
                }
                membersAdapter.notifyDataSetChanged();
                userGridview.setAdapter(membersAdapter);
            }
        });
    }


    /**
     * 清空群聊天记录
     */
    private void clearGroupHistory() {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(group.getGroupId(), EMConversationType.GroupChat);
        if (conversation != null) {
            conversation.clearAllMessages();
        }
        Toast.makeText(this, R.string.messages_are_empty, Toast.LENGTH_SHORT).show();
    }

    /**
     * 退出群组
     */
    private void exitGrop() {
        String st1 = getResources().getString(R.string.Exit_the_group_chat_failure);
        new Thread(new Runnable() {
            public void run() {
                try {
                    ChatUtil.sendCMSMessage(GROUP_TUICHU_MEMBER, groupId, mUserEntity.getUser_id() + "");
                    GroupCache.getInstance(getApplication()).deleteGroupByID(groupId);
                    EMClient.getInstance().groupManager().leaveGroup(groupId);
                    GroupMemberCache.getInstance(getApplication()).deleteGroupMember(groupId, mUserEntity.getUser_id() + "");
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Exit_the_group_chat_failure)
                                    + " " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 解散群组
     */
    private void deleteGrop() {
        final String st5 = getResources().getString(R.string.Dissolve_group_chat_tofail);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().groupManager().destroyGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), st5 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 增加群成员
     */
    private void addMembersToGroup(final String[] newmembers) {
        final String st6 = getResources().getString(R.string.Add_group_members_fail);
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())) {
                        EMClient.getInstance().groupManager().addUsersToGroup(groupId, newmembers);
                    } else {
                        // 一般成员调用invite方法
                        EMClient.getInstance().groupManager().inviteUser(groupId, newmembers, null);
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
                            updateGroup();
                            tv_title.setText(group.getGroupName() + "(" + group.getMemberCount() + memberText);
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), st6 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 群组成员gridadapter
     */
    private class GridAdapter extends ArrayAdapter<String> {

        private int res;
        public boolean isInDeleteMode;
        private List<String> objects;

        public GridAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(res, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.textView = (TextView) convertView.findViewById(R.id.tv_name);
                holder.badgeDeleteView = (ImageView) convertView.findViewById(R.id.badge_delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final LinearLayout button = (LinearLayout) convertView.findViewById(R.id.button_avatar);
            // 最后一个item，减人按钮
            if (position == getCount() - 1) {
                holder.textView.setText("");
                // 设置成删除按钮
                holder.imageView.setImageResource(R.drawable.em_smiley_minus_btn);
//				button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_minus_btn, 0, 0);
                // 如果不是创建者或者没有相应权限，不提供加减人按钮
                if (!group.getOwner().equals(EMClient.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else { // 显示删除按钮
                    if (isInDeleteMode) {
                        // 正处于删除模式下，隐藏删除按钮
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        // 正常模式
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                    }
                    final String st10 = getResources().getString(R.string.The_delete_button_is_clicked);
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EMLog.d(TAG, st10);
                            isInDeleteMode = true;
                            notifyDataSetChanged();
                        }
                    });
                }
            } else if (position == getCount() - 2) { // 添加群组成员按钮
                holder.textView.setText("");
                holder.imageView.setImageResource(R.drawable.em_smiley_add_btn);
//				button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_add_btn, 0, 0);
                // 如果不是创建者或者没有相应权限

                // 正处于删除模式下,隐藏添加按钮
                if (isInDeleteMode) {
                    convertView.setVisibility(View.INVISIBLE);
                } else {
                    convertView.setVisibility(View.VISIBLE);
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                }
                final String st11 = getResources().getString(R.string.Add_a_button_was_clicked);
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EMLog.d(TAG, st11);
                        // 进入选人页面
                        startActivityForResult((new Intent(GroupDetailsActivity.this, GroupPickContactsActivity.class)
                                .putExtra("groupId", groupId)), REQUEST_CODE_ADD_USER);
                        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                    }
                });
            } else { // 普通item，显示群组成员
                final String username = getItem(position);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                EaseUserUtils.setUserNick(username, holder.textView);
                EaseUser user = EaseUserUtils.getUserInfo(username);
                CommonUtils.loadImageView(getContext(), user.getAvatar(), R.mipmap.default_head, holder.imageView);
                if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                }
                final String st12 = getResources().getString(com.eightbears.beboy.R.string.not_delete_myself);
                final String st13 = getResources().getString(com.eightbears.beboy.R.string.Are_removed);
                final String st14 = getResources().getString(com.eightbears.beboy.R.string.Delete_failed);
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isInDeleteMode) {
                            // 如果是删除自己，return
                            if (EMClient.getInstance().getCurrentUser().equals(username)) {
                                new EaseAlertDialog(GroupDetailsActivity.this, st12).show();
                                return;
                            }
                            if (!NetUtils.hasNetwork(getApplicationContext())) {
                                Toast.makeText(getApplicationContext(), getString(com.eightbears.beboy.R.string.network_unavailable), Toast.LENGTH_SHORT).show();
                                return;
                            }
                            deleteMembersFromGroup(username);
                            ChatUtil.sendCMSMessage(GROUP_TICHU_MEMBER, PARAMS_USERS_ID, username, groupId, username);
                        } else {
                            startLocalActivity(GroupDetailsActivity.this, UserInfoActivity.class, PARAMS_USER_INFO, username);
                        }
                    }

                    /**
                     * 删除群成员
                     *
                     * @param username
                     */
                    protected void deleteMembersFromGroup(final String username) {
                        final ProgressDialog deleteDialog = new ProgressDialog(GroupDetailsActivity.this);
                        deleteDialog.setMessage(st13);
                        deleteDialog.setCanceledOnTouchOutside(false);
                        deleteDialog.show();
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    // 删除被选中的成员
                                    EMClient.getInstance().groupManager().removeUserFromGroup(groupId, username);
                                    isInDeleteMode = false;
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            deleteDialog.dismiss();
                                        }
                                    });
                                } catch (final Exception e) {
                                    deleteDialog.dismiss();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), st14 + e.getMessage(), Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }

                            }
                        }).start();
                    }
                });
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount() + 2;
        }
    }

    protected void updateGroup() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    if (pushConfigs == null) {
                        EMClient.getInstance().pushManager().getPushConfigsFromServer();
                    }

                    try {
                        group = EMClient.getInstance().groupManager().getGroupFromServer(groupId);
                        memberList.clear();
//                        EMCursorResult<String> result = null;
                        memberList.addAll(group.getMembers());
//                        do {
//                            // page size set to 20 is convenient for testing, should be applied to big value
//                            result = EMClient.getInstance().groupManager().fetchGroupMembers(groupId, result != null ? result.getCursor() : "", 20);
//                            EMLog.d(TAG, "fetchGroupMembers result.size:" + result.getData().size());
//                            memberList.addAll(result.getData());
//                        } while (result.getData().size() == 20);

                    } catch (Exception e) {
                        //e.printStackTrace();  // User may have no permission for fetch mute, fetch black list operation
                    } finally {
                        memberList.remove(group.getOwner());
                        memberList.removeAll(muteList);
                    }

                    try {
                        EMClient.getInstance().groupManager().fetchGroupAnnouncement(groupId);
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }

                    runOnUiThread(new Runnable() {
                        public void run() {
                            refreshMembersAdapter();
                            tv_title.setText(group.getGroupName() + " (" + group.getMemberCount() + "人)");
                            loadingPB.setVisibility(View.GONE);

                            if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())) {
                                // 显示解散按钮
                                exitBtn.setVisibility(View.GONE);
                                deleteBtn.setVisibility(View.VISIBLE);
                            } else {
                                // 显示退出按钮
                                exitBtn.setVisibility(View.VISIBLE);
                                deleteBtn.setVisibility(View.GONE);
                            }

                            boolean isOwner = isCurrentOwner(group);
                            exitBtn.setVisibility(isOwner ? View.GONE : View.VISIBLE);
                            deleteBtn.setVisibility(isOwner ? View.VISIBLE : View.GONE);
                        }
                    });

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            loadingPB.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }
        }).start();

    }



    private static class ViewHolder {
        ImageView imageView;
        TextView textView;
        ImageView badgeDeleteView;
    }

    private class GroupChangeListener extends EaseGroupListener {

        @Override
        public void onInvitationAccepted(String groupId, String inviter, String reason) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    memberList = group.getMembers();
                    memberList.remove(group.getOwner());
                    memberList.removeAll(muteList);
                    refreshMembersAdapter();
                }
            });
        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            finish();
        }

        @Override
        public void onGroupDestroyed(String groupId, String groupName) {
            finish();
        }

        @Override
        public void onMuteListAdded(String groupId, final List<String> mutes, final long muteExpire) {
            updateGroup();
        }

        @Override
        public void onMuteListRemoved(String groupId, final List<String> mutes) {
            updateGroup();
        }

        @Override
        public void onAdminAdded(String groupId, String administrator) {
            updateGroup();
        }

        @Override
        public void onAdminRemoved(String groupId, String administrator) {
            updateGroup();
        }

        @Override
        public void onOwnerChanged(String groupId, String newOwner, String oldOwner) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(GroupDetailsActivity.this, "onOwnerChanged", Toast.LENGTH_LONG).show();
                }
            });
            updateGroup();
        }

        @Override
        public void onMemberJoined(String groupId, String member) {
            EMLog.d(TAG, "onMemberJoined");
        }

        @Override
        public void onMemberExited(String groupId, String member) {
            updateGroup();
        }

        @Override
        public void onAnnouncementChanged(String groupId, final String announcement) {

        }

        @Override
        public void onSharedFileAdded(String groupId, final EMMucSharedFile sharedFile) {
            if (groupId.equals(GroupDetailsActivity.this.groupId)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(GroupDetailsActivity.this, "Group added a share file", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onSharedFileDeleted(String groupId, String fileId) {
            if (groupId.equals(GroupDetailsActivity.this.groupId)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(GroupDetailsActivity.this, "Group deleted a share file", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case GROUP_DIR_UPDATE:
                setDescription();
                break;
        }
    }

    @OnClick(R.id.ll_back)
    public void back() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        EMClient.getInstance().groupManager().removeGroupChangeListener(groupChangeListener);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        instance = null;

    }
}
